﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic;
using System.Web;
using System.Web.Mvc;
using SHOP.Areas.Admin.Models;
using System.Text.RegularExpressions;

namespace SHOP.Areas.Admin.Controllers
{
    public class AccountController : Controller
    {
        //
        // GET: /Admin/Account/

        //Kết nối dữ liệu
        AccountModelDataContext dataTable = new AccountModelDataContext();
        QuestionsModelsDataContext dbQuestion = new QuestionsModelsDataContext();
        LocationsModelsDataContext dbLocation = new LocationsModelsDataContext();
        HistoryModelDataContext dbHistory = new HistoryModelDataContext();
        static Random _random = new Random();

        public Constants Constants = new Constants();
        public string NameController = "account";

        [HandleError]
        public ActionResult Index()
        {
            //Delete Multi Record
            string[] items = Request.Form.GetValues("items");

            if (items != null)
            {
                foreach (var value in items)
                {
                    var ItemAccount = dataTable.accounts.Single(b => b.id == int.Parse(value));
                    dataTable.accounts.DeleteOnSubmit(ItemAccount);
                    dataTable.SubmitChanges();
                }

                return Redirect("/admin/" + NameController + "#success");
            }

            return View();
        }

        [HandleError, HttpPost]
        public ActionResult LoadContent()
        {
            string Sort_By = "";
            string Sort_Type = "";
            string Search_Type = "username";
            string KeyWord = Request.Form["keyword"];

            string[] Columns = { "username", "fullname", "email", "phone", "status", "created" };
            string sortby = Array.Find(Columns, delegate(string s) { return s == Request.Form["sort_by"]; });

            string[] Sort = { "asc", "desc" };
            string sorttype = Array.Find(Sort, delegate(string s) { return s == Request.Form["sort_type"]; });

            if (sortby != null) { Sort_By = sortby; } else { Sort_By = "id"; };
            if (sorttype != null) { Sort_Type = sorttype; } else { Sort_Type = "desc"; };

            //Pagination
            var page = int.Parse(Request.Form["page"]);
            if (KeyWord != "")
            {
                var ListItem = (from u in dataTable.accounts select u).Where(Search_Type + ".Contains(@0)", KeyWord).OrderBy(Sort_By + " " + Sort_Type).Skip((page - 1) * Constants.pageSize).Take(Constants.pageSize).ToList();
                ViewBag.numPage = (from u in dataTable.accounts select u).Where(Search_Type + ".Contains(@0)", KeyWord).Count();
                ViewBag.View = ListItem;
                
            } else {
                var ListItem = (from u in dataTable.accounts select u).Where("status != @0", 2).OrderBy(Sort_By + " " + Sort_Type).Skip((page - 1) * Constants.pageSize).Take(Constants.pageSize).ToList();
                ViewBag.numPage = (from u in dataTable.accounts select u).Where("status != @0", 2).Count();
                ViewBag.View = ListItem;
            }

            ViewBag.Page = page;
            ViewBag.Keyword = KeyWord;
            ViewBag.Sort_By = Sort_By;
            ViewBag.Sort_Type = Sort_Type;
            ViewBag.pageSize = Constants.pageSize;

            return View();
        }

        [HandleError]
        public ActionResult Update()
        {
            if (Request.QueryString["id"] != null && System.Text.RegularExpressions.Regex.IsMatch(Request.QueryString["id"], @"\d"))
            {
                var id = Convert.ToInt32(Request.QueryString["id"]);
                var ListItem = dataTable.accounts.SingleOrDefault(b => b.id == id);
                ViewBag.View = ListItem;
            }
            return View();
        }

        public bool check_user(string user)
        {
            bool check = true;
            if(dataTable.accounts.Count(c => c.username == user) > 0){
                check = false;
            }
            return check;
        }

        [HandleError]
        public ActionResult Save()
        {
            HttpContext.Response.AppendHeader("Access-Control-Allow-Origin", "*");

            var json = "";

            if (Request.Form["id"] == "")
            {
                //Insert
                if (ModelState.IsValid && Request.Form["password"].Length >= 5 && Request.Form["password"] != "" && check_user(Request.Form["username"]))
                {

                    Random rand = new Random();
                    int toSkip = rand.Next(0, dbQuestion.questions.Count());

                    var ListItem = new account();

                    ListItem.username = Request.Form["username"];
                    ListItem.password = Constants.md5(Request.Form["password"]);
                    ListItem.email = Request.Form["email"];
                    ListItem.fullname = Request.Form["fullname"];
                    ListItem.currents = dbQuestion.questions.Skip(toSkip).Take(1).First().id;
                    ListItem.address = Request.Form["address"];
                    ListItem.latitude = decimal.Parse(Request.Form["lat"]);
                    ListItem.longtitude = decimal.Parse(Request.Form["lng"]);
                    ListItem.random_key = Constants.md5(DateTime.Now.ToString());
                    ListItem.status = (Request.Form["status"] != null) ? 1 : 0;
                    ListItem.changed = DateTime.Now;
                    ListItem.created = DateTime.Now;

                    dataTable.accounts.InsertOnSubmit(ListItem);
                    dataTable.SubmitChanges();

                    json = "success";
                }
                else
                {
                    json = "fail";
                }

            }else{

                //Update
                var id = int.Parse(Request.Form["id"]);
                int recCount = dataTable.accounts.Count(b => b.id == id);

                if (ModelState.IsValid && recCount > 0)
                {
                    var ListItem = dataTable.accounts.Single(b => b.id == id);

                    ListItem.username = Request.Form["username"];
                    
                    if(Request.Form["password"] != null)
                        ListItem.password = Constants.md5(Request.Form["password"]);

                    ListItem.email = Request.Form["email"];
                    ListItem.fullname = Request.Form["fullname"];
                    ListItem.address    = Request.Form["address"];
                    ListItem.random_key = Constants.md5(DateTime.Now.ToString());
                    ListItem.status   = 1;
                    ListItem.changed  = DateTime.Now;
                    dataTable.SubmitChanges();

                    json = "success";
                }
                else
                {
                    json = "fail";
                }
            }

            return Json( new{ st = json });
        }

        [HandleError, HttpPost]
        public ActionResult Status()
        {
            //Update
            var json = "";

            int id = Convert.ToInt32(Request.Form["id"]);
            int recCount = dataTable.accounts.Count(b => b.id == id);

            if (recCount > 0)
            {
                var ListItem = dataTable.accounts.Single(b => b.id == id);
                ListItem.status = int.Parse(Request.Form["status"]);
                dataTable.SubmitChanges();
                json = "success";
            }
            else
            {
                json = "fail";
            }

            return Json(new { st = json }, JsonRequestBehavior.AllowGet);
        }

        //Random Question
        public static void Shuffle<T>(T[] array)
        {
            var random = _random;
            for (int i = array.Length; i > 1; i--)
            {
                int j = random.Next(i);
                T tmp = array[j];
                array[j] = array[i - 1];
                array[i - 1] = tmp;
            }
        }

        [HandleError]
        public ActionResult Info()
        {

            HttpContext.Response.AppendHeader("Access-Control-Allow-Origin", "*");

            //Update
            var json = "";
            var result = new Dictionary<string,object>();
            string random_key = Request.Form["access_token"];
            int recCount = dataTable.accounts.Count(b => b.random_key == random_key);
            string answer_a="", answer_b="", answer_c="", answer_d="";
            if (recCount > 0)
            {
                var Account = dataTable.accounts.Single(b => b.random_key == random_key);
                //Current Question
                var QuestionCurrent = dbQuestion.questions.Single(b => b.id == Account.currents);
                //Location of Question
                var Location = dbLocation.locations.Single(b => b.id == QuestionCurrent.locationid);

                string[] arrCauTraLoi = QuestionCurrent.answers.Split(new string[] { "<%%>" }, StringSplitOptions.None);

                Shuffle(arrCauTraLoi);
                int Count = 1;
                
                foreach (string value in arrCauTraLoi)
                {
                    string[] cA = value.Split(new string[] { "<@@>" }, StringSplitOptions.None);
                    if (Count == 1)
                    {
                        answer_a = cA[0].ToString();
                    }
                    else if (Count == 2)
                    {
                        answer_b = cA[0].ToString();
                    }
                    else if (Count == 3)
                    {
                        answer_c = cA[0].ToString();
                    }
                    else
                    {
                        answer_d = cA[0].ToString();
                    }
                    Count++;
                }

                result.Add("question",QuestionCurrent.contents);
                result.Add("a", answer_a);
                result.Add("b", answer_b);
                result.Add("c", answer_c);
                result.Add("d", answer_d);
                result.Add("question_id", QuestionCurrent.id);
                result.Add("location_name", Location.name);
                result.Add("location_description", Location.description);
                result.Add("location_address", Location.address);
                result.Add("location_latitude", Location.latitude);
                result.Add("location_longitude", Location.longitude);
                json = "success";
            }
            else
            {
                json = "fail";
            }

            return Json(new { st = json, data = result }, JsonRequestBehavior.AllowGet);
        }

        [HandleError]
        public ActionResult CheckUser()
        {

            HttpContext.Response.AppendHeader("Access-Control-Allow-Origin", "*");

            //Update
            var json = "";
            var result = new Dictionary<string, object>();
            string username = Request.Form["username"];
            string password = Constants.md5(Request.Form["password"]);
            int recCount = dataTable.accounts.Count(b => b.username == username && b.password == password);
            if (recCount > 0)
            {
                var Account = dataTable.accounts.Single(b => b.username == username && b.password == password);
                result.Add("id", Account.id);
                result.Add("username", Account.username);
                result.Add("fulname", Account.fullname);
                result.Add("email", Account.email);
                result.Add("address", Account.address.Trim());
                result.Add("image", Account.image);
                result.Add("longtitude", Account.longtitude);
                result.Add("latitude", Account.latitude);
                result.Add("random_key", Account.random_key.Trim());
                json = "success";
            }
            else
            {
                json = "fail";
            }

            return Json(new { st = json, data = result}, JsonRequestBehavior.AllowGet);
        }

        [HandleError]
        public ActionResult UpdateInfo()
        {

            HttpContext.Response.AppendHeader("Access-Control-Allow-Origin", "*");

            //Update
            var json = "";
            var result = new Dictionary<string, object>();
            string random_key = Request.Form["access_token"].Trim();
            int questionID = int.Parse(Request.Form["id"].Trim());
            string listQuestionComplete = "";
            string answer = Request.Form["answer"].Trim();

            //string random_key = Request.QueryString["access_token"].Trim();
            //int questionID = int.Parse(Request.QueryString["id"].Trim());
            //string answer = Request.QueryString["answer"].Trim();

            int checkComp = 0;
            int recCount = dataTable.accounts.Count(b => b.random_key == random_key);
            if (recCount > 0)
            {
                var Account = dataTable.accounts.Single(b => b.random_key == random_key);
                var Question = dbQuestion.questions.Single(b => b.id == questionID);
                //Check Complete
                if (Account.complete != null)
                {
                    string[] comp = Account.complete.Split(',');
                    if (comp.Length != 0)
                    {
                        for (int i = 0; i < comp.Length; i++)
                        {
                            if (Convert.ToInt32(comp[i]) == questionID)
                            {
                                checkComp++;
                            }
                        }
                    }
                }

                //Nếu câu hỏi không thuộc các câu đã trả lời (Luông đúng nếu Current đúng)
                if (checkComp == 0)
                {
                    if (Account.complete == null || Account.complete == "")
                    {
                        Account.complete = questionID.ToString();
                        listQuestionComplete = Account.complete.Trim();
                    }
                    else
                    {
                        Account.complete = Account.complete.Trim() + "," + questionID.ToString();
                        listQuestionComplete = Account.complete.Trim();
                    }

                    List<string> ta = listQuestionComplete.Trim().Split(',').ToList<string>();

                    Random rand = new Random();
                    int toSkip = rand.Next(0, dbQuestion.questions.Where(c => !ta.Contains(c.id.ToString())).Count());
                    var ListQues = (from c in dbQuestion.questions where !ta.Contains(c.id.ToString()) select c).ToList();

                    int count = 0;
                    foreach (var item in ListQues)
                    {
                        if (count == toSkip)
                        {
                            Account.currents = item.id;
                        }
                        count++;
                    }

                    dataTable.SubmitChanges();
                    string pattern = answer + "<@@>1";
                    Regex myRegex = new Regex(pattern);
                    string[] sKetQua = myRegex.Split(Question.answers);
                    if (sKetQua.Length > 0)
                    {
                        Question.pass++;
                        json = "success";
                    }
                    else
                    {
                        Question.fail++;
                        json = "fail";
                    }
                    dbQuestion.SubmitChanges();
                }
                else
                {
                    json = "errors";
                }
                //Question Current
                //json = "success";
            }
            else
            {
                json = "fail";
            }
            return Json(new { st = json}, JsonRequestBehavior.AllowGet);
        }

        [HandleError]
        public ActionResult History()
        {
            HttpContext.Response.AppendHeader("Access-Control-Allow-Origin", "*");

            var json = "";
            //Account ID
            int accountid = int.Parse(Request.Form["id"]);
            //Address
            string address = Request.Form["address"];
            //Type 1 : Lưu lịch sử, 2 : Đã đến, 3 : Yêu thích
            int type = int.Parse(Request.Form["type"]);
            // Kinh độ, Vĩ độ
            string latitude = Request.Form["lat"];
            string longitude = Request.Form["lng"];
            string name = Request.Form["name"];
            //Insert
            if (address == null || accountid == 0)
            {
                json = "fail";
            }
            else {
                //Insert
                //Kiểm tra xem user có tồn tại hay không
                var Account = dataTable.accounts.Single(b => b.id == accountid);
                if (Account != null) {
                    //Kiểm tra type đó đã tồn tại chưa
                    //var CheckHistory = dbHistory.histories.Single(b => b.type == type);
                    var History = new history();
                    History.accountid = accountid;
                    History.name = name;
                    History.address = address;
                    History.type = type;
                    if (latitude != null)
                    {
                        History.latitude = latitude;
                    }
                    if (longitude != null)
                    {
                        History.longitude = longitude;
                    }
                    History.created = DateTime.Now;
                    History.changed = DateTime.Now;
                    dbHistory.histories.InsertOnSubmit(History);
                    dbHistory.SubmitChanges();
                    json = "success";    
                }else
                {
                    json = "fail";
                }
            }
            return Json(new { st = json}, JsonRequestBehavior.AllowGet);
        }
    }
}
